package com.wxtf.platform.tools;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONArray;

/**
 * <li>Title: Common.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.tools</li>
 * <li>Description: </li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Aug 3, 2012 1:34:41 PM</li>
 *
 * @author chun_chang
 * @version 1.0.0.0
 *
 */
public class Common{
	
	public static String splitCss(String filePath) throws Exception {
		File file = new File(filePath);
		if(!(file.exists())) {
			throw new Exception("指定的文件不存在");
		}

		String cssString = loadAFileToString(file);
		cssString = replaceBlank(cssString);
		String[] items = cssString.split("}");

		String str = "";
		String str1 = "";
		List<Map<String, String>> rtnList = new ArrayList<Map<String, String>>();
		for(String css: items) {
			Map<String, String> map = new HashMap<String, String>();
			String tem = css;
			str = css.substring(1, css.indexOf("{"));
			if("l-icon".equals(str)){
				continue;
			}
			str = str.replaceAll("l-icon-", "");
			str1 = tem.substring(tem.indexOf("(")+2, tem.indexOf(")") - 1);
			map.put("key", str);
			map.put("icon", str1.toLowerCase());
			rtnList.add(map);
		}
		JSONArray jsonArray = JSONArray.fromObject(rtnList);
		String rtnString = jsonArray.toString();
		jsonArray.clear();
		return rtnString;
	}

	public static String replaceBlank(String str) {
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(str);
		str = m.replaceAll("");
		return str;
	}

	public static String loadAFileToString(File f) throws IOException {
		BufferedReader br = null;
		String ret = null;
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
			String line = null;
			StringBuffer sb = new StringBuffer((int) f.length());
			while((line = br.readLine()) != null) {
				sb.append(line).append("\r");
			}
			ret = sb.toString();
		} finally {
			if(br != null)
				try {
					br.close();
				} catch(Exception localException) {
				}
		}
		return ret;
	}

	public static void copyFile(File sourceFile, File targetFile) throws IOException {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} finally {
			// 关闭流
			if(inBuff != null)
				inBuff.close();
			if(outBuff != null)
				outBuff.close();
		}
	}


	
}
